package com.hsd.commons.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.hsd.survey.model.HsdModelQuestion;

/**
 * JSON工具类
 */
@SuppressWarnings("serial")
public class JSONLibUtil implements java.io.Serializable
{

	public static String serializeObjectToJSON(Object obj)
	{
		if (obj == null)
			return null;
		else
		{
			JSONObject jsonObject = JSONObject
					.fromObject(obj);
			return jsonObject.toString();
		}
	}

	@SuppressWarnings("unchecked")
	public static Object deserializeJSONToObject(
			String json, Class rootClass,
			Map classMapping)
	{
		JSONObject jsonObject = JSONObject.fromObject(json);
		if (classMapping != null)
			return JSONObject.toBean(
					jsonObject,
					rootClass,
					classMapping);
		else
			return JSONObject.toBean(jsonObject, rootClass);
	}

	@SuppressWarnings("unchecked")
	public static Map deserializeJSONToMap(String json) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		Iterator<?> it = jsonObject.keys();
		Map map = null;
		while (it.hasNext()) {
			Object key = it.next();
			Object o = jsonObject.get(key);
			if(map == null )map = new HashMap();
			map.put(key, o);
		}
		return map;
	}
	
	/**
	 * 解析Json数组到Collection
	 * @param json
	 * @return
	 */
	public static Collection<?> deserializeJSONArrayToMap(String json){
		JSONArray jsonArray = JSONArray.fromObject(json);
		Collection<?> collection = JSONArray.toCollection(jsonArray);
		if(null != collection && !collection.isEmpty()){
			return collection;
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
//		String json = "{pagelist:[{\"id\":\"1381120560159\",\"index\":0},{\"id\":\"1381120545552\",\"index\":1}]}";
//		json = "[{\"id\":\"1381120560159\",\"index\":0},{\"id\":\"1381120545552\",\"index\":1}]";
//		JSONArray jsonArray = JSONArray.fromObject(json);
//		System.out.println(jsonArray.size());
		
		HsdModelQuestion answer = new HsdModelQuestion();
		System.out.println(JSONObject.fromObject(answer));
		
		/*Map m = deserializeJSONToMap(s);
		System.out.println(m.size());
		List applicantMap = (List)m.get("pagelist");
		System.out.println(applicantMap);
		if(applicantMap!=null&&applicantMap instanceof List){
			Iterator iterator = applicantMap.iterator();
			while(iterator.hasNext()) {
				Map v = (Map)iterator.next();
				System.out.println(v.get("id"));
			}
		}
		*/
		// 
		
		
	}
}
